﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Xml.Serialization;
using ObservadorPeplau.API;
using ObservadorPeplau.API.Buffer;
using ObservadorPeplau.API.Business;

namespace ObservadorPeplau.API.Business
{
    public class Discussion
    {
        private List<Comment> _comments = new List<Comment>();
        
        public string Url { get; set; }
        public string Title { get; set; }
        public Author Author { get; set; }
        public DateTime DateTime { get; set; }
        public int NumberOfComments { get; set; }

        [XmlIgnore]
        public List<Comment> Comments
        {
            get { return _comments; }
            set { _comments = value; }
        }

        [XmlIgnore]
        public bool IsStared
        {
            get { return DiscussionManager.IsMarked(this, Constants.DiscussionStaredKey); }
            set { DiscussionManager.SetMarked(this, Constants.DiscussionStaredKey, value); }
        }

        [XmlIgnore]
        public bool IsRead
        {
            get
            {
                if (!IsStared)
                    return DiscussionManager.IsMarked(this, Constants.DiscussionReadKey);
                return !HasUnreadComments;
            }
            set
            {
                if (!IsStared)                
                    DiscussionManager.SetMarked(this, Constants.DiscussionReadKey, value);
            }
        }

        [XmlIgnore]
        public bool HasUnreadComments
        {
            get
            {                
                return IsStared && GetReadComments(false).Count>0;
            }
        }

        public List<Comment> GetUnreadComments(Comment comment = null)
        {
            return GetReadComments(false, comment);
        }

        public List<Comment> GetReadComments(bool isRead, Comment comment = null)
        {
            if (Comments==null)
                return new List<Comment>();

            var lstComments = (comment == null) ? Comments : comment.Children;

            var readComments = lstComments.Where(p => p.IsRead == isRead).ToList();
            foreach (Comment childComment in lstComments)
                readComments.AddRange(GetReadComments(isRead,childComment));

            return readComments;
        }
    }
}
